from django.shortcuts import render
from django.http import HttpResponse
from rest_framework.views import APIView
from .models import *
from rest_framework.response import Response
from .ser import *


# Create your views here.

def hello(request):
    return HttpResponse('欢迎使用django')


class Usermanage(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        address = request.data.get('address')
        age = request.data.get('age')
        User.objects.create(username=username, password=password, age=age)
        return HttpResponse('OK')


class ClassM(APIView):
    def get(self, request):
        cls = Cclass.objects.all()
        ser = ClassSer(cls, many=True)
        return Response({"code": 200, 'list': ser.data})

    def post(self, request):
        ser = CuserSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({'code': 20010})


class CbanjiM(APIView):
    def get(self, request):
        userid = int(request.GET.get('userid'))
        user = Cuser.objects.filter(id=userid).first()
        ser = SCuserSer(user)
        return Response({'code': 200, 'list': ser.data})

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = Cuser.objects.filter(username=username).first()
        if user:
            if password == user.password:
                return Response({'code': 200, 'userid': user.id})
            else:
                return Response({'code': 20010})
        else:
            return Response({'code': 20011})

    def put(self, request):
        userid = request.GET.get('userid')
        user = Cuser.objects.filter(id=userid).first()
        ser = SCuserSer(user).data
        print(ser)
        if ser['cla']['types'] == 1:
            cla = Cclass.objects.filter(types=2).first()
            user.cla_id = cla.id
            user.save()
            return Response({'code': 200})
        elif ser['cla']['types'] == 2:
            cla = Cclass.objects.filter(types=3).first()
            user.cla_id = cla.id
            user.save()
            return Response({'code': 200})
        else:
            return Response({'code': 20020})
